/**
 * @class ExtGames.Pack
 * @extends Ext.util.Observable
 * Represents a complete pack of cards
 */
ExtGames.Pack = function(config) {
  config = config || {};
  
  this.cards = [];
  
  this.suits   = ExtGames.Card.prototype.suits;
  this.numbers = ExtGames.Card.prototype.numbers;

  this.getTopCard = function() {
    return this.cards.shift();
  };
  
 
  this.shuffle = function(times) {
    var times = times || 1;
    
    //shuffle the pack as many times as required
    for (var x = times - 1; x >= 0; x--) {
      var i = this.cards.length;
      
      while (--i) {
        var j = Math.floor(Math.random() * (i + 1));
        var a = this.cards[i];
        var b = this.cards[j];
        
        this.cards[i] = b;
        this.cards[j] = a;
      }
    }
  };
  
  this.getCardString = function() {
	  var c = [];
	  for (var i = 0; i < this.cards.length; i++) {
		  c.push(this.cards[i].toObject());
	  }
	  
	  return JSON.stringify(c);
  };
  
  this.getNumCards = function() {
	  return this.cards.length;
  };
  
  this.populateCards = function(cardString) {
	  var c = eval('('+cardString+')');
	  for (var i = 0; i < c.length; i++) {
		  var card = new ExtGames.Card({
		        suit:   c[i].suit,
		        number: c[i].number,
		        joker: c[i].joker,
		        pack:   this,
		        listeners: {
		          'dblclick': {
		            scope: this,
		            fn:    function(card) {this.fireEvent('carddblclick', card, this);}
		          }
		        }
		      });
		  this.cards.push(card);
	  }
	  
	  console.log('Pack initialized: '+this.getCardString());
  };
  
  this.createCards = function(config) {
	  this.cards = [];
  	
	  if (config.cards) {
		  this.populateCards(config.cards);
	  }
	  else {
	  	
	  	  var decks = config.decks || 1;
	  	  var jokers = config.jokers || 0;
	  
	  	  for (var d = 0; d < decks; d++) {
			  //add the cards
			  for (var i=0; i < this.suits.length; i++) {
			    for (var j=0; j < this.numbers.length; j++) {
			      var card = new ExtGames.Card({
			        suit:   this.suits[i],
			        number: this.numbers[j],
			        pack:   this,
			        listeners: {
			          'dblclick': {
			            scope: this,
			            fn:    function(card) {this.fireEvent('carddblclick', card, this);}
			          }
			        }
			      });
			      this.cards.push(card);
			    }
			  }
			  
			  for (var i=0; i < jokers; i++) {
			  	var card = new ExtGames.Card({
					joker: true,
			        pack:   this,
			        listeners: {
			          'dblclick': {
			            scope: this,
			            fn:    function(card) {this.fireEvent('carddblclick', card, this);}
			          }
			        }
			      });
			      this.cards.push(card);
			  }
		  }
		  
		  this.shuffle(3);
		  	  	  
	  }
  };
	  
	this.createCards(config);
		
};
   


